package com.jerry.boot.core.web;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jerry.boot.core.Utils;
import com.jerry.boot.core.base.JConfigureProperties;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class JBootFilter implements Filter {

    @Autowired(required = false)
    private List<JFilter> filters;

    @Autowired(required = false)
    private JFilterChain filterChain;

    @Resource
    private JConfigureProperties jConfigureProperties;

    private List<String> excludeUrls;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        if (CollUtil.isNotEmpty(filters) && filterChain != null) {
            filterChain.setFilters(filters);
        }
        String urlStr = jConfigureProperties.getExcludeUrls();
        if (StrUtil.isNotBlank(urlStr)) {
            excludeUrls = StrUtil.split(urlStr, ",");
        }

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getServletPath();
        if (!Utils.matches(url, excludeUrls)) {
            if (filterChain != null) {
                if (!filterChain.handleRequest(request, response)) {
                    return;
                }
            }
        }
        chain.doFilter(request, response);
    }

    public List<JFilter> getFilters() {
        return filters;
    }

    public JFilterChain getFilterChain() {
        return filterChain;
    }

}
